//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    
    // 登录

   

  

    let a = new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                if (res.errMsg === "getUserInfo:ok"){
                  this.globalData.data = res;
                  resolve({
                    iv:res.iv,
                    encryptedData: res.encryptedData,
                  });
                }
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              }
            })
          } else {
            wx.authorize({
              scope: 'scope.userInfo',
              success(res) {
                wx.getUserInfo({
                  success: res => {
                    if (this.userInfoReadyCallback) {
                      this.userInfoReadyCallback(res)
                    }
                  }
                })
              }
            })
          };
        }
      });
    });

    let b = new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            resolve({
              appid: this.globalData.appid,
              secret: this.globalData.secret,
              code:res.code,
            });
          }
        }
      })

    });

    var p = Promise.all([a, b]);
    p.then((val)=> {
      let l = new Promise((resolve,reject)=>{
        wx.request({
          url: `${this.globalData.ip}/wxLogin`,
          type: "post",
          data: Object.assign(val[0], val[1]),
          success: data => {
            this.globalData.userMes = data.data;
            resolve();
          }
        })
      }).then(() =>{
        wx.request({
          url: `${this.globalData.ip}/login`,
          data: {
            unionid: this.globalData.userMes.unionid
          },
          success: res => {
            this.globalData.isLogin = true;
            this.globalData.header = {
              'Cookie': `JSESSIONID=${res.data.mes.sessionId}`
            };
            console.log('登录成功');
          }
        })
      });
    });
  },
  globalData: {
    userInfo: null,
    userMes:null,
    isLogin:false,'Cookie': '',
    header:null,
    appid:'wxa9be21d3ba03a9fc',
    secret:'8284e793177d6a01c7e75970ee178cbe',
    ip:"http://192.168.10.183:8000"
  }
})